var express = require("express");
var axios = require('axios');
const { StatusCodes } = require("http-status-codes");
let multiparty = require('multiparty');
const fs1 = require("fs-extra");
const path = require("path");
const exp = require("constants");
// const { CHUNK_SIZE } = require("../client/src/constant");
const PUBLIC_DIR = path.resolve(__dirname, "../upload");

const TEMP_DIR = path.resolve(__dirname, "temp");
const CHUNK_SIZE = 100 * 1024 * 1024;
//存放上传并合并好的文件
fs1.ensureDirSync(PUBLIC_DIR);
//存放分片的文件
fs1.ensureDirSync(TEMP_DIR);
// const router = express();

var router = express.Router();
const sharp = require("sharp");
const pixelmatch = require("pixelmatch");
const { PNG } = require("pngjs");
const fs = require("fs");
const { UsersModel, TypesModel, VideosModel } = require("../model/model");
/* GET home page. */
router.get("/", function (req, res) {
  res.render("index", { title: "Express" });
});
//注册
router.post("/regist", async (req, res) => {
  let { username } = req.body;
  let user = await UsersModel.findOne({ username });
  if (user) {
    return res.send({ msg: "用户名已存在" });
  }
  await UsersModel.create(req.body);
  res.send({ msg: "注册成功" });
});

//获取当前用户信息
router.get("/concern", async (req, res) => {
  let username = req.query.account;
  console.log(username);
  let data = await UsersModel.find({ username })
  res.send(data)
})

//登录 
router.post('/login', async (req, res) => {
  console.log(PUBLIC_DIR);
  let { username, password, avatar } = req.body

  let user = await UsersModel.findOne({ username })
  let list = await UsersModel.find()

  if (avatar) {
    let avatars = avatar.split(';base64,')[1]
    //将base64转换为buffer
    let buffer1 = Buffer.from(avatars, 'base64');
    //将buffer转换为png
    const image1 = await sharp(buffer1).png().toBuffer();
    // console.log(image1);

    const png1 = PNG.sync.read(await image1);
    //如果有照片的base64 就对其进行对比

    for (let i = 0; i < list.length; i++) {


      if (list[i].face) {
        const lists = list[i].face.split(';base64,')[1]

        let buffer2 = Buffer.from(lists, 'base64');
        try {
          const image2 = await sharp(buffer2).png().toBuffer();
          const png2 = PNG.sync.read(await image2);
          //  Compare the images with pixelmatch
          const numDiffPixels = pixelmatch(png1.data, png2.data, null, png1.width, png1.height, { threshold: 0.1 });
          fs.writeFileSync('output1.png', image1);
          fs.writeFileSync('output.png', image2);
          let num = 1 - numDiffPixels / (png1.width * png1.height)
          console.log(num);

          if (num > 0.55) {
            let user_id = list[i]._id
            let copy = {}
            copy.account = user.account
            copy.avatar = user.avatar
            copy.res = user.name
            return res.send({ msg: '登录成功', user_id: user._id, copy })
          } else {
            if (i >= list.length - 1) {

              res.send({ msg: '头像不一致' })

            }
          }
        } catch (error) {
          console.error(error);
        }
      }


    }
  } else {
    if (user) {
      if (password == user.password) {
        let copy = {}
        copy.account = user.account
        copy.avatar = user.avatar
        copy.res = user.name
        return res.send({ msg: '登录成功', user_id: user._id, copy })
      } else {
        res.send({ msg: '密码错误' })
      }
    } else {
      res.send({ msg: '用户不存在' })
    }
  }



}
);
//录入上传的视频到数据库
router.post('/upinfo', async (req, res) => {
  let { filename, _id } = req.body
  console.log(_id);
  await VideosModel.create({ video: filename, uid: _id })
  res.send('添加成功')
})
//上传图片
router.post('/upload2', (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (data1, data2, imgData) => {
    res.send('https://www.pabzibo.live:3001/upload/' + imgData.file[0].path)
  })
})
//主页渲染
router.get("/look", async (req, res) => {
  let vllist = await VideosModel.find().populate("types").populate("uid")
  res.send({
    code: 201,
    vllist
  })
})
//临时登录
router.post('/lo', async (req, res) => {
  let { username, password } = req.body
  let user = await UsersModel.find({ username })
  if (user.length > 0) {
    if (password == user[0].password) {
      let data = await UsersModel.find({ username, password }).populate('concern')
      res.send({ msg: '登录成功', data })
    } else {
      res.send({ msg: '密码错误' })
    }

  } else {
    res.send({ msg: '用户不存在' })
  }


})
router.post("/upload/:filename", async (req, res, next) => {
  //通过路径参数获取文件名
  const { filename } = req.params;
  //   console.log("upload filename", filename);
  //通过查询参数获取分片名
  const { chunkFileName } = req.query;
  //   console.log("chunkFileName", chunkFileName);
  //创建用户保存此文件的分片的目录
  const chunkDir = path.resolve(TEMP_DIR, filename);
  //分片的文件路径
  const chunkFilePath = path.resolve(chunkDir, chunkFileName);
  //先确保分片目录存在
  await fs1.ensureDir(chunkDir);
  //创建此文件的可写流
  const ws = fs1.createWriteStream(chunkFilePath, {});
  //后面会实现暂停操作，如果客户端点击了暂停按钮，会取消上传操作，取消之后会在服务器触发请求对象的aborted事件
  //aborted事件触发之后，会关闭此可写流
  req.on("aborted", () => {
    ws.close();
  });
  //使用管道的方式把请求中的请求体流数据写入到文件中
  try {
    await pipeStream(req, ws);
    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});
// router.post()


router.get("/merge/:filename", async (req, res, next) => {
  //通过路径参数获取文件名
  const { filename } = req.params;
  //   console.log("merge filename", filename);
  try {
    await mergeChunks(filename);
    res.json({ success: true });
  } catch (error) {
    next(error);
  }
});

router.get("/verify/:filename", async (req, res, next) => {
  const { filename } = req.params;
  //先获取文件在服务器的路径
  const filePath = path.resolve(PUBLIC_DIR, filename);
  //判断是文件在服务器端是否存在
  const isExist = await fs1.pathExists(filePath);
  //如果已经存在了，则直接返回不需要上传了
  if (isExist) {
    res.json({ success: true, needUpload: false });
  }
  //如果没有此文件，则意味着服务器还需要你上传此文件
  res.json({ success: true, needUpload: true });
});

// 验证文件是否已经上传
// router.get("/verify/:filename", async (req, res) => {
//   const { filename } = req.params;
//   const filePath = path.resolve(PUBLIC_DIR, filename);
//   try {
//     // 检查文件是否存在
//     const isExist = await fs.pathExists(filePath);
//     if (isExist) {
//       // 文件已上传，返回信息给前端
//       res.json({ success: true, needUpload: false });
//     } else {
//       // 文件尚未上传
//       res.json({ success: true, needUpload: true });
//     }
//   } catch (error) {
//     // 处理错误
//     console.error("Error verifying file:", error);
//     res.status(500).json({ success: false, error: "Error verifying file" });
//   }
// });

async function mergeChunks(filename) {
  const mergedFilePath = path.resolve(PUBLIC_DIR, filename);
  const chunkDir = path.resolve(TEMP_DIR, filename);
  const chunkFiles = await fs1.readdir(chunkDir);
  //对分片索引进行升序排列
  chunkFiles.sort((a, b) => Number(a.split("-")[1]) - Number(b.split("-")[1]));
  try {
    //为了提高性能，我们在这时可以分片并行写入
    const pipes = chunkFiles.map((chunkFile, index) => {
      return pipeStream(
        fs1.createReadStream(path.resolve(chunkDir, chunkFile), {
          autoClose: true,
        }),
        fs1.createWriteStream(mergedFilePath, {
          start: index * CHUNK_SIZE,
        })
      );
    });
    l;
    //并发把每个分片的数据写入到目标文件中去
    await Promise.all(pipes);
    //删除分片的文件和文件夹
    await fs1.rmdir(chunkDir, { recursive: true });
  } catch (error) {
    next(error);
  }
}
function pipeStream(rs, ws) {
  return new Promise((resolve, reject) => {
    //把可读流中的数据写入可写流中
    rs.pipe(ws).on("finish", resolve).on("error", reject);
  });
}

/* 随机视频播放·代理服务 */
router.get('/randomVideo', async function (req, res,) {
  console.log('random');
  // 获取外部链接
  let answer = await axios.get('https://api.yujn.cn/api/manzhan.php?type=text')
  // 外部链接的数据
  let videoUrl = answer.data
  // 发送
  res.send({ videoUrl })
});

module.exports = router;
